//
//  TestViewController1.m
//  MSDemo
//
//  Created by mac on 2021/7/26.
//

#import "TestViewController1.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayerManager.h"
#import "ConvertAudioFile.h"

#define ETRECORD_RATE 11025.0
#define ENCODE_MP3    1

@interface TestViewController1 ()
<
AVAudioRecorderDelegate
>

@property (nonatomic, strong) NSString *mp3Path; ///< mp3文件路径
@property (nonatomic, strong) NSString *cafPath; ///< caf文件路径

@property (nonatomic, strong) NSTimer  *timer;
@property (nonatomic, strong) UILabel  *timeLabel;
@property (nonatomic, strong) UIButton *recordButton;
@property (nonatomic, strong) UIButton *stopRecordButton;

@property (nonatomic, strong) AVAudioRecorder *audioRecorder;

@end

@implementation TestViewController1
{
    NSInteger time;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"录音";
}


#pragma mark - event

- (void)recoredButton:(id)sender
{
    // 重置录音机
    if (_audioRecorder)
    {
        [self cleanMp3File];
        [self cleanCafFile];
        _audioRecorder = nil;
        time = 0;
        [self destoryTimer];
    }
    
    if (![self.audioRecorder isRecording])
    {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
        {
            MSLog(@"Error creating session: %@", [sessionError description]);
        }
        else
        {
            [session setActive:YES error:nil];
        }
        
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(record)
                                                    userInfo:nil
                                                     repeats:YES];
        [self.audioRecorder record];

         MSLog(@"录音开始");
        
#if ENCODE_MP3
         [[ConvertAudioFile sharedInstance] conventToMp3WithCafFilePath:self.cafPath
                                                           mp3FilePath:self.mp3Path
                                                            sampleRate:ETRECORD_RATE
                                                              callback:^(BOOL result)
         {
             if (result)
             {
                 MSLog(@"mp3 file compression sucesss");
             }
         }];
#endif
        
    }
    else
    {
        MSLog(@"is  recording now  ....");
    }

}

- (void)record
{
    time ++;
    self.timeLabel.text = [self timeFormatted:(int)time];
    
//    [self.recordButton ]
}


- (void)stopRecord:(id)sender
{
 
    if ([self.audioRecorder isRecording])
    {
        MSLog(@"完成");
        [self destoryTimer];
        [self.audioRecorder stop];
    }

#if !ENCODE_MP3
    [ConvertAudioFile conventToMp3WithCafFilePath:self.cafPath
                                      mp3FilePath:self.mp3Path
                                       sampleRate:ETRECORD_RATE
                                         callback:^(BOOL result) {
                                             
        MSLog(@"转码结果 ------ %d", result);
    }];
    
#endif
}

- (void)playVoice:(id)sender
{
    if ([self.audioRecorder isRecording])
    {
        MSLog(@"--------  正在录制中...");
        [self stopRecord:nil];
        return;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:self.cafPath isDirectory:&isDir];
    if (!isDirExist)
    {
        MSLog(@"--------  录音文件不存在...");
        return;
    }
    
    NSURL *url = [NSURL fileURLWithPath:self.mp3Path];
    
    [[PlayerManager sharedInstance] playWithVoiceURL:url];
    
    if (self.timer) { [self destoryTimer]; }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                   target:self
                                                 selector:@selector(play)
                                                 userInfo:nil
                                                  repeats:YES];
}

- (void)play
{
     self.timeLabel.text = [NSString stringWithFormat:@"%@ / %@", [self timeFormatted:[PlayerManager sharedInstance].currentTime], [self timeFormatted:[PlayerManager sharedInstance].finishTime]];
}

- (void)pausePaly:(id)sender
{
    [[PlayerManager sharedInstance] pause];
}


- (void)destoryTimer
{
    if (self.timer)
    {
        [self.timer invalidate];
        self.timer = nil;
        MSLog(@"----- timer destory");
    }
}


- (NSString *)timeFormatted:(NSInteger)totalSeconds
{
    
    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;
    NSInteger hours = totalSeconds / 3600;
    if (hours <= 0)
    {
        return [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes, (long)seconds];
    }
    
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours, (long)minutes, (long)seconds];
}

/* audioRecorderDidFinishRecording:successfully: is called when a recording has been finished or stopped. This method is NOT called if the recorder is stopped due to an interruption. */
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    if (flag)
    {
        MSLog(@"----- 录音  完毕");
#if ENCODE_MP3
        [[ConvertAudioFile sharedInstance] sendEndRecord];;
#endif
    }
}


#pragma mark -
/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
- (NSDictionary *)getAudioSetting
{
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //编码格式
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //采样率（电话采样率@8000）
    [dicM setObject:@(ETRECORD_RATE) forKey:AVSampleRateKey];
    //声道数
    [dicM setObject:@(2) forKey:AVNumberOfChannelsKey];
    //线性采样位数-比特率（8 16 24 32）
    [dicM setObject:@(16) forKey:AVLinearPCMBitDepthKey];
    //录音质量
    [dicM setObject:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
    return dicM;
}

/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
-(NSURL *)getSavePath
{
    //  在Documents目录下创建一个名为FileData的文件夹
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioData"];
    MSLog(@"%@",path);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if(!(isDirExist && isDir))
        
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir)
        {
            MSLog(@"创建文件夹失败！");
        }
        MSLog(@"创建文件夹成功，文件路径%@",path);
    }
    NSString *fileName = @"record";
    NSString *cafFileName = [NSString stringWithFormat:@"%@.caf", fileName];
    NSString *mp3FileName = [NSString stringWithFormat:@"%@.mp3", fileName];
    
    NSString *cafPath = [path stringByAppendingPathComponent:cafFileName];
    NSString *mp3Path = [path stringByAppendingPathComponent:mp3FileName];
    
    self.mp3Path = mp3Path;
    self.cafPath = cafPath;
    
    MSLog(@"file path:%@",cafPath);
    
    NSURL *url=[NSURL fileURLWithPath:cafPath];
    return url;
}

- (void)cleanCafFile
{
    if (!ms_stringIsEmpty(self.cafPath))
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = FALSE;
        BOOL isDirExist = [fileManager fileExistsAtPath:self.cafPath isDirectory:&isDir];
        if (isDirExist) {
            [fileManager removeItemAtPath:self.cafPath error:nil];
            MSLog(@"  xxx.caf  file   already delete");
        }
    }
}

- (void)cleanMp3File
{
    if (!ms_stringIsEmpty(self.mp3Path))
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = FALSE;
        BOOL isDirExist = [fileManager fileExistsAtPath:self.mp3Path isDirectory:&isDir];
        if (isDirExist) {
            [fileManager removeItemAtPath:self.mp3Path error:nil];
            MSLog(@"  xxx.mp3  file   already delete");
        }
    }
}


- (void)convertMp3
{
        [[ConvertAudioFile sharedInstance] conventToMp3WithCafFilePath:self.cafPath
                                                           mp3FilePath:self.mp3Path
                                                            sampleRate:ETRECORD_RATE callback:^(BOOL result)
        {
            MSLog(@"---- 转码完成  --- result %d  ---- ", result);
        }];;
 

}


#pragma mark - UI
- (void)updateViewConstraints
{
    [super updateViewConstraints];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(100);
        make.centerX.equalTo(self.view);
    }];
    
    [self.recordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.timeLabel.mas_bottom).offset(50);
        make.height.mas_equalTo(150);
    }];
    
    [self.stopRecordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.timeLabel.mas_bottom).offset(50);
        make.height.mas_equalTo(150);
    }];
    
    NSArray *views = @[self.recordButton, self.stopRecordButton];
    [views mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                    withFixedItemLength:150
                            leadSpacing:30
                            tailSpacing:30];
}


#pragma mark - getter

/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
- (AVAudioRecorder *)audioRecorder
{
    if (!_audioRecorder)
    {
        //7.0第一次运行会提示，是否允许使用麦克风
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
        {
            MSLog(@"Error creating session: %@", [sessionError description]);
        }
        else
        {
            [session setActive:YES error:nil];
        }
        
        //创建录音文件保存路径
        NSURL *url= [self getSavePath];
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate=self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        [_audioRecorder prepareToRecord];
        if (error) {
            MSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

- (UILabel *)timeLabel
{
    if (!_timeLabel)
    {
        _timeLabel = ms_newLabel();
        
        [_timeLabel ms_makeChains:^(MSChainMaker * _Nonnull make) {
            make
            .ms_text(@"00:00:00")
            .ms_textColor(MS_HEX_COLOR(0x333333))
            .ms_font(MS_SYSTEM_FONT_OF_SIZE(16))
            .ms_cornerRadii(10)
            .ms_lineWidth(2)
            .ms_lineColor(MS_HEX_COLOR(0x333333))
            .ms_lineDashPhase(3)
            .ms_lineDashPattern(@[@3,@1])
            .ms_addToSuperView(self.view);
        }];
    }
    
    return _timeLabel;
}

- (UIButton *)recordButton
{
    if (!_recordButton)
    {
        _recordButton = ms_newButton();
        
        [_recordButton ms_makeChains:^(MSChainMaker * _Nonnull make) {
            
            make
            .ms_backgroundColor(MS_HEX_COLOR(0xF7F7F7))
            .ms_titleFont(MS_SYSTEM_FONT_OF_SIZE(13))
            .ms_titleColor(MS_HEX_COLOR(0x333333), UIControlStateNormal)
            .ms_title(@"开始录音", UIControlStateNormal)
            .ms_cornerRadii(75)
            .ms_lineWidth(2)
            .ms_lineColor(UIColor.greenColor)
            .ms_addTarget(self, @selector(recoredButton:))
            .ms_addToSuperView(self.view);
        }];
    }
    
    return _recordButton;
}

- (UIButton *)stopRecordButton
{
    if (!_stopRecordButton)
    {
        _stopRecordButton = ms_newButton();
        
        [_stopRecordButton ms_makeChains:^(MSChainMaker * _Nonnull make) {
            
            make
            .ms_backgroundColor(MS_HEX_COLOR(0xF7F7F7))
            .ms_titleFont(MS_SYSTEM_FONT_OF_SIZE(13))
            .ms_titleColor(MS_HEX_COLOR(0x333333), UIControlStateNormal)
            .ms_title(@"停止录音", UIControlStateNormal)
            .ms_topLeftCornerRadii(75)
            .ms_topRightCornerRadii(75)
            .ms_bottomLeftCornerRadii(75)
            .ms_lineWidth(2)
            .ms_lineColor(UIColor.redColor)
            .ms_lineDashPattern(@[@5,@2])
            .ms_lineDashPhase(30)
            .ms_addLayerAnimation(@"strokeEnd" ,3, @0, @1, 1)
            .ms_addTarget(self, @selector(stopRecord:))
            .ms_addToSuperView(self.view);
        }];
    }
    
    return _stopRecordButton;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
